<template>
	<view>
		<scroll-view class="visitor" scroll-y="true" @refresherrefresh="initData()" @scrolltolower="getVisitors">
			<uni-list :border="false">
				<view class="list-tip">
					仅展示30天内的访客，并访客记录仅自己可见
				</view>
				<u-empty mode="data" v-if="personList.length==0 && status === 'nomore'" text="暂无访客记录"></u-empty>
				<!-- 自定义右侧内容 -->
				<uni-list-chat :clickable="true" @click="goToOthersPage(item,index)"  :avatar-circle="true" :title="item.nickName" :note="item.visitorCreatime?formatDateTime(item.visitorCreatime)+' 查看了你的主页':'查看了你的主页'" :avatar="item.avatar"  :border="false" v-for="(item,index) in personList">
					<view class="slot-image" v-if="!item.relationType">
						<u-button size="mini" text="添加" @click.native.stop="onAddFriend(item,index)"></u-button>
						<u-icon class="slot-icon" name="arrow-right" color="#000000" size="16"></u-icon>

					</view>
					<view class="slot-image" v-else>
						<!-- <u-button text="私聊" @click.native.stop="onChat(item)" size="mini" color="#F82F41"></u-button> -->
						<u-icon class="slot-icon" name="arrow-right" color="#000000" size="16"></u-icon>
					</view>
				</uni-list-chat>
			</uni-list>
			<u-loadmore 
				:status="status"
				:textSize="12"
				:loading-text="loadingText" 
				:loadmore-text="loadmoreText" 
				:nomore-text="nomoreText" 
				color="rgb(144, 147, 153 , 0.9)"
				lineColor="rgb(144, 147, 153, 0.2)"
				line
			 />
		</scroll-view>
	</view>
</template>

<script>
	import {
		getVisitorRecord,
		getClientFollow
	} from '@/request/api.js'
	export default {
		data() {
			return {
				pageNum:1,
				personList:[],
				total: 0, // 总记录数
				status: 'loadmore', // 加载状态，可选值为 'loadmore', 'loading', 'nomore'
				loadingText: '努力加载中',
				loadmoreText: '轻轻上拉',
				nomoreText: '拉到底了哦~',
				isLoading: false, // 防止重复加载的节流阀
			}
		},
		onLoad() {
			this.getVisitors()
		},
		methods: {
			formatDateTime(time) {
				if(!time) return null
				const date = new Date(time);
			    let year = date.getFullYear();
			    let month = ("0" + (date.getMonth() + 1)).slice(-2);
			    let day = ("0" + date.getDate()).slice(-2);
			    let hours = ("0" + date.getHours()).slice(-2);
			    let minutes = ("0" + date.getMinutes()).slice(-2);
			    let seconds = ("0" + date.getSeconds()).slice(-2);
			    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			initData(){
				this.pageNum = 1;
				this.personList = [];
				this.total = 0;
				this.status = 'loadmore';
				this.isLoading = false;
				this.getVisitors();
				// 如果您在 pages.json 中配置了 enablePullDownRefresh，可以用这个停止刷新动画
				setTimeout(() => {
					uni.stopPullDownRefresh();
				}, 500);
			},
			getVisitors(){
				// 如果正在加载或已经没有更多数据，则直接返回
				if (this.isLoading || this.status === 'nomore') {
					return;
				}

				this.isLoading = true;
				this.status = 'loading'; // 设置为加载中状态

				let params = {
					pageNum: this.pageNum,
					pageSize: 15
				}
				getVisitorRecord(params).then(res => {
					if (res.data && res.data.code === 200) {
						const newVisitors = res.data.rows || [];
						this.total = res.data.total; // 从接口获取总数

						// 将新获取的数据追加到personList
						this.personList = [...this.personList, ...newVisitors];
						
						// 判断是否还有更多数据
						if (this.personList.length >= this.total) {
							this.status = 'nomore'; // 没有更多数据
						} else {
							this.status = 'loadmore'; // 准备加载下一页
							this.pageNum++; // 页码增加，为下次请求做准备
						}
					} else {
						// 接口请求失败或返回错误码
						this.status = 'loadmore';
						uni.showToast({ title: '加载失败', icon: 'none' });
					}
				}).catch(err => {
					// 网络或其他请求错误
					this.status = 'loadmore';
					uni.showToast({ title: '网络错误', icon: 'none' });
				}).finally(() => {
					// 请求完成后，无论成功失败，都将isLoading设为false
					this.isLoading = false;
				});
			},
			// 添加好友
			onAddFriend(item,index){
				getClientFollow({userId:item.userId}).then(res=>{
					this.personList[index].isFriend = true
				})
				console.log("添加好友");
			},
			onChat(item){
				uni.navigateTo({
					url: '/pages_sub/user/chat/chat?userId='+item.id,
				});
			},
			goToOthersPage(userItem, indexInYourList) { // userItem 是你当前列表中的一项
			        let initialData = {
			            userId: userItem.userId,
			            isFollowed: userItem.isFollowed > 0 ? true : false // 或者你的关注状态字段
			        };
			        uni.navigateTo({
			            url: '/pages_sub/user/others/others',
			            events: {
			                returnData: (returnedData) => {
			                    if (returnedData.userId === userItem.userId && typeof returnedData.isFollowed !== 'undefined') {
			                        // 假设你的列表是 this.personList
			                        // 确保响应式更新
			                        this.$set(this.personList[indexInYourList], 'isFollowed', returnedData.isFollowed ? 1 : 0);
			                        // 或者如果 isFollowed 直接是 boolean
			                        // this.$set(this.personList[indexInYourList], 'isFollowed', returnedData.isFollowed);
			                    }
			                }
			            },
			            success: (res) => {
			                res.eventChannel.emit('sendInitData', { data: JSON.stringify(initialData) });
			            }
			        });
			}
		}
	}
</script>

<style lang="scss">
	.visitor{
		padding: 20rpx 0;
		height: calc(100vh - 40rpx);
	}
	.list-tip{
		text-align: center;
		font-size: 24rpx;
		margin: 50rpx 0;
	}

	.slot-image {
		font-size: 24rpx;
		line-height: 40rpx;
		color: #999999;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.slot-icon {
		margin-left: 20rpx;
	}
</style>
